package com.photoeditor.demo.ui.activity.edit;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.transition.Slide;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;

import com.photoeditor.R;
import com.photoeditor.demo.app.ActionConstant;
import com.photoeditor.demo.app.XActivity;
import com.photoeditor.demo.model.bean.BitmapBean;
import com.photoeditor.demo.model.image.util.ImageHelper;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.model.share.ShareImageDialogHelp;
import com.photoeditor.demo.statistics.NotifyStoreUpdateStatisticUtil;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.ui.activity.HomeActivity;
import com.photoeditor.demo.ui.dialog.DialogShow;
import com.photoeditor.demo.ui.dialog.DialogStatistic;
import com.photoeditor.demo.ui.dialog.IDialog;
import com.photoeditor.demo.ui.dialog.IRateDialogListener;
import com.photoeditor.demo.ui.dialog.RateGuide;
import com.photoeditor.demo.ui.fragement.HomeFragment;
import com.photoeditor.demo.ui.widget.image.ImagePreviewView;
import com.photoeditor.demo.util.FetcherHolder;
import com.photoeditor.demo.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

public class ImagePreviewActivity extends XActivity {

    public static final int REFRESH_DATA = 0x100;

    public static final int REQUEST_CODE_START_GALLERY = 0x101;

    public static final int REFRESH_DATA_ACTION_VIEW = 0x102;

    public final static String ENTRANCE = "entrance";

    public final static String POSITION = "position";

    public final static String BUCKET_ID = "bucket_id";

    public static final String NEED_RESFREH = "need_refresh";

    public static final String IS_NEED_SHARE = "is_need_share";

    public final static int FROM_BEAUTY = 1;

    public final static int FROM_GALLERY = 2;

    public final static int FROM_OTHER_GALLERY = 4;

    public final static int FROM_ADVANCE_FEATURE = 6;

    public final static int FROM_OTHER = 0;

    private ImagePreviewView mImageView;
    public static int SCREEN_WIDTH = 0;
    public static int SCREEN_HEIGHT = 0;
    // IWXAPI 是第三方app和微信通信的openapi接口
//    private IWXAPI api;

    private int mEntrance;

    //0 不用刷新  1刷新当前界面 2全部刷新
    private int isNeedRefresh = REFRESH_NONE;

    public static final int REFRESH_CURRENT = 1;

    public static final int REFRESH_CURRENT_AND_PRIVATE = 2;

    public static final int REFRESH_CURRENT_AND_GALLERY = 3;

    public static final int REFRESH_CURRENT_AND_OTHER_GALLERY = 4;

    public static final int REFRESH_ALL = 5;

    public static final int REFRESH_NONE = 0;

    /**
     * 进入我的相册的指定位置
     */
    public static final String ACTION_SHOW_MY_ALBUM = "action_show_my_album";

    private boolean mIsWidgetIn = false;

    private boolean mIsViewAndShare = false;

    private boolean isNeedStartShare = false;

    private ShareImageDialogHelp mShareHelp;

    //从主页btn点击进来
    private String mMainButtonEntrance;

    private final int WHERE = 0;
    private IRateDialogListener mListener = new IRateDialogListener() {
        @Override
        public void onScoreClick(int score) {
//            if (score >= 4) {
//                //好评
//                DialogStatistic.rateGoodComm(/*WHERE*/getIntent().getIntExtra(ENTRANCE, 0));
//            } else {
//                DialogStatistic.rateBadComm(/*WHERE*/getIntent().getIntExtra(ENTRANCE, 0));
//            }
        }

        @Override
        public void onReasonSubmit(List<String> reasons) {
            ToastUtil.showToast(getString(R.string.dialog_virtual_bat_sure_toast));
        }

        @Override
        public void onCloseClick() {
//            DialogStatistic.rateClose(/*WHERE*/getIntent().getIntExtra(ENTRANCE, 0));
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//		requestWindowFeature(Window.FEATURE_NO_TITLE);

        Intent i = getIntent();
        mEntrance = i.getIntExtra(ENTRANCE, FROM_OTHER);
        isNeedStartShare = i.getBooleanExtra(IS_NEED_SHARE, false);

        mMainButtonEntrance = i.getStringExtra(HomeFragment.EXTRA_MAIN_BTN_ENTRANCE);

        mShareHelp = new ShareImageDialogHelp(this);

        DisplayMetrics dm = this.getResources().getDisplayMetrics();
        SCREEN_WIDTH = dm.widthPixels;
        SCREEN_HEIGHT = dm.heightPixels;

        boolean landscape = false;
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            landscape = true;
        }

        boolean isNeedAnimation = false;
        /**
         * 初始化缓存
         */
        FetcherHolder.getPreviewBitmapCache();

        String action = i.getAction();
        Uri uri = null;
        /**
         * 处理系统的android.intent.action.VIEW Intent
         */
        if (action != null && (action.equals(Intent.ACTION_VIEW) || ActionConstant.Actions.ACTION_MOTION_VIEW_AND_SHARE.equals(action))) {
            if (ActionConstant.Actions.ACTION_MOTION_VIEW_AND_SHARE.equals(action)) {
                mIsViewAndShare = true;
            } else {
            }
            if (uri == null) {
                uri = i.getData();
            }
            if (uri != null) {
                ArrayList<BitmapBean> beans = new ArrayList<BitmapBean>(1);
                BitmapBean bean = ImageHelper.getInterBitmapBeanFormUri(this, uri);
                if (bean == null) {
                    finish();
                    return;
                }
                beans.add(bean);
                mImageView = new ImagePreviewView(this, false, landscape, false);
                mImageView.setData(beans);
            } else {
                finish();
                return;
            }
        } else if (action != null && ACTION_SHOW_MY_ALBUM.equals(action)) {
            mIsWidgetIn = true;
            int position = i.getIntExtra(POSITION, 0);
            mImageView = new ImagePreviewView(this, landscape, position);
        } else {
            if (savedInstanceState != null) {
                ArrayList<BitmapBean> beans = savedInstanceState.getParcelableArrayList("uri");
                //特殊情况  针对某些应用会重启我们的预览界面
                if (beans == null || beans.size() == 0) {
                    mEntrance = savedInstanceState.getInt(ENTRANCE);
                    int position = savedInstanceState.getInt("position");
                    if (mEntrance == FROM_GALLERY) {
                        mImageView = new ImagePreviewView(this, landscape, position);
                    } else {
                        mImageView = new ImagePreviewView(this, landscape, position);
                    }
                } else {//横屏的情况
                    mImageView = new ImagePreviewView(this, false, landscape, (mEntrance == FROM_OTHER_GALLERY));
                    mImageView.setData(beans, savedInstanceState.getInt("position"), savedInstanceState.getInt("hasAd"), savedInstanceState.getInt("adPosition"));
                    isNeedRefresh = savedInstanceState.getInt(NEED_RESFREH);
                }
            } else {
                if (mEntrance == FROM_GALLERY) {
                    int position = i.getIntExtra(POSITION, 0);
                    mImageView = new ImagePreviewView(this, landscape, position);
                    isNeedAnimation = true;
                } else if (mEntrance == FROM_OTHER_GALLERY) {
                    int position = i.getIntExtra(POSITION, 0);
                    mImageView = new ImagePreviewView(this, landscape, position, true);
                    isNeedAnimation = true;
                } else {
                    mImageView = new ImagePreviewView(this, true, landscape, false);
                }
            }
        }

        setContentView(mImageView);

        if (isNeedAnimation) {
            setupWindowAnimations();
        }

//        DialogShow.showRateGuideDialog(DialogShow.RateGuideEntrance.ENTRANCE_2, this, RateGuide.ACTION_USE_FUNC, null,
//                new IDialog.Listener() {
//                    @Override
//                    public void yes() {
//                        DialogStatistic.rateShow(/*WHERE*/getIntent().getIntExtra(ENTRANCE, 0));
//                    }
//                },
//                mListener);
    }


    private void setupWindowAnimations() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Slide slide = new Slide();
            slide.setSlideEdge(Gravity.BOTTOM);
            getWindow().setEnterTransition(slide);

            Slide sd = new Slide();
            sd.setSlideEdge(Gravity.TOP);
            getWindow().setExitTransition(sd);
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        try {
            super.onRestoreInstanceState(savedInstanceState);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        mImageView.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mImageView != null) {
            mImageView.onStop();
        }
        System.gc();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mImageView != null) {
            if (isNeedStartShare) {
                isNeedStartShare = false;
                Intent i = getIntent();
                i.putExtra(IS_NEED_SHARE, isNeedStartShare);//防止横屏再出现分享页面
            }
        }
        ShareImageDialogHelp.deleteInsImg();
        StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_EDITOR, StatisticsConstant.UMENG_CUSTOM_KEY_FUNCTION,
                StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_SETTING_VALUE_SHARE_CLICK + StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
                        SPDataManager.getFunctionEntrance() + StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_SHOW);

        DialogShow.showRateGuideDialog(DialogShow.RateGuideEntrance.ENTRANCE_2, this, RateGuide.ACTION_USE_FUNC, null,
                null,
                mListener, mEntrance);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (mImageView != null) {
            mImageView.onDestroy();
        }
        if (mShareHelp != null) {
            mShareHelp.destory();
        }
        super.onDestroy();
        System.gc();
    }

    /**
     * 处理分享界面弹出时的情况
     */
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        boolean flag = mImageView.onKeyUp(keyCode, event);
        if (flag) {
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mImageView.onKeyBack()) {
                return true;
            }
            if (mEntrance == FROM_GALLERY || mEntrance == FROM_OTHER_GALLERY) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    finishAfterTransition();
                } else {
                    finish();
//					overridePendingTransition(R.anim.activity_bottom_out, 0);
                }
            } else if (mEntrance == ImagePreviewActivity.FROM_ADVANCE_FEATURE) {
                //goto home page
                HomeActivity.back2Home(this);
            } else {
                finish();
                overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
            }
            return true;
        }

        if (keyCode == KeyEvent.KEYCODE_MENU) {
            mImageView.clickMenu();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    private void showRate(Intent data) {
        if (data == null) {
            return;
        }
//        Bundle rateBundle = data.getBundleExtra(RateGuide.INTENT_RATE_EFFECT_BUNDLE);
//        RateGuide.Builder rateBuilder = RateGuide.getRateBuilder(rateBundle, false);
//        if (rateBuilder != null) {
//            rateBuilder.show(this);
//        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REFRESH_DATA && resultCode == RESULT_OK) {
            final Uri uri = data.getData();
            if (mEntrance == FROM_OTHER_GALLERY) {
                mImageView.gettingData(0, false);
                setIsNeedRefresh(ImagePreviewActivity.REFRESH_CURRENT_AND_GALLERY);
            } else {
                mImageView.addUri(uri);
                if (mEntrance == ImagePreviewActivity.FROM_GALLERY) {
                    setIsNeedRefresh(ImagePreviewActivity.REFRESH_CURRENT_AND_OTHER_GALLERY);
                }
            }
            showRate(data);
            if ("finish".equals(data.getStringExtra("finish"))) {
                finish();
            }
        } else if (requestCode == REQUEST_CODE_START_GALLERY) {
            if (getEntrance() == FROM_OTHER_GALLERY) {
                mImageView.startGettingOtherDataTask(mImageView.mLastPosition, mImageView.getOtherBucketId());
            } else {
                mImageView.gettingData(mImageView.mLastPosition, false);
            }
            showRate(data);
        } else if (requestCode == REFRESH_DATA_ACTION_VIEW && resultCode == RESULT_OK) {
            mImageView.gettingData(0, false);
            showRate(data);
        }

    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (outState != null) {
            outState.putParcelableArrayList("uri", mImageView.getData());
            outState.putInt("position", mImageView.getPosition());
            outState.putInt(NEED_RESFREH, isNeedRefresh);
            outState.putInt(ENTRANCE, mEntrance);
        }
        super.onSaveInstanceState(outState);
    }

    public int getEntrance() {
        return mEntrance;
    }

    public void setIsNeedRefresh(int flag) {
        isNeedRefresh = flag;
    }

    public void finishWithNothing() {
        if (mEntrance == FROM_GALLERY || mEntrance == FROM_OTHER_GALLERY) {
            Intent i = new Intent();
            i.putExtra(NEED_RESFREH, isNeedRefresh);
            setResult(RESULT_OK, i);
        }
        super.finish();
    }

    @Override
    public void finish() {
        if (mEntrance == FROM_GALLERY || mEntrance == FROM_OTHER_GALLERY) {
            Intent i = new Intent();
            i.putExtra(NEED_RESFREH, isNeedRefresh);
            setResult(RESULT_OK, i);
        }
        NotifyStoreUpdateStatisticUtil.clear();
        super.finish();
    }

    @Override
    public void finishAfterTransition() {
        if (mEntrance == FROM_GALLERY || mEntrance == FROM_OTHER_GALLERY) {
            Intent i = new Intent();
            i.putExtra(NEED_RESFREH, isNeedRefresh);
            setResult(RESULT_OK, i);
        }
        super.finishAfterTransition();
    }

    public boolean getIsViewAndShare() {
        return mIsViewAndShare;
    }

    public void showShareDialog(Bitmap bitmap, BitmapBean bean) {
        //mShareHelp.showShareDialog(bitmap, bean);
        mShareHelp.setMainButtonEntrance(mMainButtonEntrance);
        mShareHelp.showShareDialogBottom(bean);
    }

    public static void startPicturePreviewActivity(Context context, boolean isPrivate) {
        Intent intent = new Intent();
        intent.setClass(context, ImagePreviewActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    /**
     * 会跳转Share
     *
     * @param context
     * @param isPrivate
     */
    public static void startPicturePreviewActivityAndStartShare(Context context, boolean isPrivate, Uri uri) {
        Intent intent = new Intent();
        intent.setClass(context, ImagePreviewActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.setData(uri);
        intent.putExtra(IS_NEED_SHARE, true);
        context.startActivity(intent);
    }

    public static void startGallerySelectMotionViewAndShare(Context context, Uri uri) {
        Intent intent = new Intent(ActionConstant.Actions.ACTION_MOTION_VIEW_AND_SHARE);
        intent.setComponent(new ComponentName(context, ImagePreviewActivity.class));
        intent.setData(uri);
        context.startActivity(intent);
    }

    /**
     * 启动相册选择图片进行拼接
     *
     * @param context
     */
    public static void startGallerySelectCollageImages(Context context) {
        Intent intent = new Intent(ActionConstant.Actions.ACTION_SELECT_IMAGES_TO_COLLAGE);
        intent.setComponent(new ComponentName(context, ImagePreviewActivity.class));
        intent.setType("image/*");
        context.startActivity(intent);
    }

    /**
     * 会跳转Share
     *
     * @param context
     */
    public static void startPictureViewActivityAndStartShare(Context context, Uri uri) {
        Intent intent = new Intent();
        intent.setClass(context, ImagePreviewActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.setData(uri);
        intent.putExtra(IS_NEED_SHARE, true);
        context.startActivity(intent);
    }

    public static void startPictureViewActivityAndStartShare(Context context, Uri uri, Bundle additionExtras, String mainButtonEntrance, int entrance) {
        Intent intent = new Intent();
        intent.setClass(context, ImagePreviewActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.setData(uri);
        intent.putExtra(IS_NEED_SHARE, true);
        intent.putExtra(HomeFragment.EXTRA_MAIN_BTN_ENTRANCE, mainButtonEntrance);
        if (additionExtras != null) {
            intent.putExtra(RateGuide.INTENT_RATE_EFFECT_BUNDLE, additionExtras);
        }
        intent.putExtra(ENTRANCE, entrance);
        context.startActivity(intent);
    }

    public static void startPictureViewActivityAndStartShare(Context context, Uri uri, Bundle additionExtras, String mainButtonEntrance, int entrance, int degree) {
        Intent intent = new Intent();
        intent.setClass(context, ImagePreviewActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.setData(uri);
        intent.putExtra(IS_NEED_SHARE, true);
        intent.putExtra("degree", degree);
        intent.putExtra(HomeFragment.EXTRA_MAIN_BTN_ENTRANCE, mainButtonEntrance);
        if (additionExtras != null) {
            intent.putExtra(RateGuide.INTENT_RATE_EFFECT_BUNDLE, additionExtras);
        }
        intent.putExtra(ENTRANCE, entrance);
        context.startActivity(intent);
    }

    public static void startPictureViewActivityAndStartShare(Context context, Uri uri, Bundle additionExtras, String mainButtonEntrance) {
        Intent intent = new Intent();
        intent.setClass(context, ImagePreviewActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.setData(uri);
        intent.putExtra(IS_NEED_SHARE, true);
        intent.putExtra(HomeFragment.EXTRA_MAIN_BTN_ENTRANCE, mainButtonEntrance);
        if (additionExtras != null) {
            intent.putExtra(RateGuide.INTENT_RATE_EFFECT_BUNDLE, additionExtras);
        }
        context.startActivity(intent);
    }

    public void statisticsMainBtnPreviewDelete() {
        if (!TextUtils.isEmpty(mMainButtonEntrance)) {
            StatisticsUtils.statisticsMainBtnPreviewDelete(mMainButtonEntrance);
        }
    }

    public void statisticsMainBtnPreviewEdit() {
        if (!TextUtils.isEmpty(mMainButtonEntrance)) {
            StatisticsUtils.statisticsMainBtnPreviewEdit(mMainButtonEntrance);
        }
    }

}
